// pages/moment/moment.js
let app = getApp()

import req from '../../utils/req';
import utils from '../../utils/utils';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabIndex: 0,
    tabList: ["树洞", "攻略"],
    moment: [],
    strategy: [],
    currentMomentPage: 1,
    currentStrategyPage: 1,
    totalMoment: 0,
    totalStrategy: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      userInfo: app.globalData.userInfo,
      moment: [],
      strategy: [],
    })
    this.getMoment("search")
    this.getStrategy("search")
  },
  bindChangeTab(e) {
    this.setData({
      tabIndex: e.currentTarget.dataset.index
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.dataset.img, // 当前显示图片的http链接
      urls: e.currentTarget.dataset.image // 需要预览的图片http链接列表
    })
  },
  getMoment(type) {
    type === 'refrash' ? wx.showNavigationBarLoading() : '' //刷新加载
    const data = {
      page: this.data.currentMomentPage
    }
    req.get('加载中', '/moment/getMoment', data, (res) => {
      const data = res.data
      data.list.forEach(e1 => {
        const images = []
        e1['images'].forEach(e2 => {
          images.push(e2.url)
        })
        e1.images = images
        e1['createTime'] = utils.timeFormat(e1['createTime'])
      });
      this.setData({
        totalMoment: data.total,
        moment: this.data.moment.concat(data.list)
      })
      if (type === 'refrash') {
        wx.hideNavigationBarLoading(); //完成停止加载图标
        wx.stopPullDownRefresh();
        utils.toast('success', '刷新成功', 500)
      }
    })
  },
  getStrategy(type) {
    type === 'refrash' ? wx.showNavigationBarLoading() : '' //刷新加载
    const data = {
      page: this.data.currentStrategyPage,
      delState: 1
    }
    req.get('加载中', '/moment/getStrategy', data, (res) => {
      const data = res.data
      data.list.forEach(e1 => {
        const images = []
        let taps = e1['taps'].split(',')
        e1['images'].forEach(e2 => {
          images.push(e2.url)
        })
        e1.images = images
        e1.taps = taps
        e1['createTime'] = utils.timeFormat(e1['createTime'])
      });
      this.setData({
        totalStrategy: data.total,
        strategy: this.data.strategy.concat(data.list)
      })
      if (type === 'refrash') {
        wx.hideNavigationBarLoading(); //完成停止加载图标
        wx.stopPullDownRefresh();
        utils.toast('success', '刷新成功', 500)
      }
    })
  },
  postMoment() {
    wx.showActionSheet({
      itemList: ['树洞', '攻略'],
      success: function (res) {
        if (!res.cancel) {
          const type = res.tapIndex === 0 ? 'normal' : 'strategy'
          wx.navigateTo({
            url: `../postMoment/postMoment?type=${type}`,
          })
        }
      }
    });
  },

  del(e) {
    let that = this
    wx.showModal({
      title: '提示',
      content: '确认删除?',
      success: function (res) {
        if (res.confirm) {
          const data = {
            mid: e.currentTarget.dataset.mid
          }
          req.post('删除中', '/moment/deleteMoment', data, (res) => {
            if (res.status === 200) {
              utils.toast('success', res.msg)
              const moment = that.data.moment
              moment.splice(e.currentTarget.dataset.idx, 1)
              that.setData({
                moment,
                totalMoment: that.data.totalMoment - 1
              })
            } else {
              utils.toast('error', res.msg)
            }
          })
        }
      }
    })
  },
  goToDetail(e) {
    const data = e.currentTarget.dataset.item
    let url = '../detail/detail?'
    Object.keys(data).forEach(e => {
      url += e + '=' + data[e] + '&'
    });
    wx.navigateTo({
      url: url
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const type = 'refrash';
    if (this.data.tabIndex === 0) {
      this.setData({
        currentMomentPage: 1,
        totalMoment: 0,
        moment: [],
      })
      this.getMoment(type)
    } else {
      this.setData({
        currentStrategyPage: 1,
        totalStrategy: 0,
        strategy: []
      })
      this.getStrategy(type)
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.tabIndex === 0) {
      if (this.data.moment.length < this.data.totalMoment) {
        const page = this.data.currentMomentPage + 1
        this.setData({
          currentMomentPage: page
        })
        this.getMoment();
      } else {
        utils.toast('none', '到底啦')
      }
    } else {
      if (this.data.strategy.length < this.data.totalStrategy) {
        const page = this.data.currentStrategyPage + 1
        this.setData({
          currentStrategyPage: page
        })
        this.getStrategy();
      } else {
        utils.toast('none', '到底啦')
      }
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})